package com.lemon.action;

import java.util.List;
import java.util.Map;

import org.apache.struts2.dispatcher.HttpParameters;
import org.apache.struts2.dispatcher.Parameter;

import com.lemon.domain.Authorize;
import com.lemon.domain.Role;
import com.lemon.service.AuthorizeService;
import com.lemon.service.RoleService;
import com.lemon.util.MapUtils;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

/**
 * 权限管理
 */
public class AuthorizeAction extends ActionSupport implements ModelDriven<Authorize> {

	private static final long serialVersionUID = 1L;

	private RoleService roleService = new RoleService();
	private AuthorizeService authorizeService = new AuthorizeService();
	private Authorize authorize = new Authorize();

	/**
	 * 角色授权
	 */
	@Override
	public String execute() throws Exception {
		authorizeService.update(authorize);
		return SUCCESS;
	}
	
	/**
	 * 跳转到角色授权页面
	 * 
	 * @return
	 */
	public String toAuthorize() {
		ActionContext context = ActionContext.getContext();
		List<Role> roles = roleService.list();
		context.put("roles", roles);

		return SUCCESS;
	}

	// json数据集合
	private Map<String, Object> json;

	public String resultJSON() {
		ActionContext context = ActionContext.getContext();
		String param = getParam(context, "id");
		Long id = Long.valueOf(param);
		//查询到角色中的权限
		Authorize authorize = authorizeService.get(id);
		//将权限对象转换成map集合
		json = MapUtils.convertToMap(authorize);

		return SUCCESS;
	}

	/**
	 * 封装了参数获取
	 * 
	 * @param context
	 * @param key
	 * @return
	 */
	private String getParam(ActionContext context, String key) {
		HttpParameters parameters = context.getParameters();
		Parameter param = parameters.get(key);
		return param.getValue();
	}

	@Override
	public Authorize getModel() {
		return authorize;
	}

	public Map<String, Object> getJson() {
		return json;
	}

	public void setJson(Map<String, Object> json) {
		this.json = json;
	}

}
